<template>
    <div class="bodyBox">
        <div class="returnBtn" @click="hendleReturnBtn">
            <up-icon name="arrow-left" bold size="20"></up-icon>
        </div>
        <!-- <div class="mainBox" @change="swiperChange" @touchstart="touchStart" @touchend="touchEnd"> -->
        <!-- <scroll-view id="scrollView" class="mainBox" scroll-y :style="{ height: boxHeight + 'px' }"
            :scroll-top="scrollLeftTop" :scroll-with-animation='false' refresher-enabled
            :refresher-triggered="triggered" @refresherrefresh="onRefresh" @scrolltolower="onBottom"
            @change="swiperChange" @touchstart="touchStart" @touchend="touchEnd"> -->

        <view class="notice">
            <view class="center">
                <swiper :style="{ height: boxHeight - 30 + 'px' }" vertical :duration="swiperDuration"
                    :current="swiperCurrent" @change="onSwiperChange">
                    <swiper-item v-for="(item, index) in listData" :key="index" :class="`listItem${index}`">
                        <!-- <div class="mainBoxItem" ref="mainBoxRef"> -->
                        <span class="titleItem">{{ item.funplay_title }}</span>
                        <div class="imgBox">
                            <image :src="item.uerr_sign" v-if="item.isPreview"></image>
                            <image :src="item.uerr_sign" v-else @click="toUser(item.user_code)"
                                :disabled="item.isPreview">
                            </image>
                            <span v-if="item.isPreview" :disabled="item.isPreview">{{ item.user_name }}</span>
                            <span v-else @click="toUser(item.user_code)" :disabled="item.isPreview">{{ item.user_name
                                }}</span>
                            <div class="imgBoxBtnList" v-if="!item.isPreview">
                                <u-button size="mini" type="" :text="$t('attention')" v-if="!item.is_follow"
                                    :disabled="disablePullup" @click="attention(item, index)" :loading="btnLoading"
                                    :loadingText="' '"></u-button>
                                <up-button size="mini" class="pinkBtn" v-else :disabled="disablePullup"
                                    @click="attention2(item, index)">{{
                                        $t('havepaidattention') }}</up-button>
                            </div>
                        </div>
                        <!-- !disablePullup ||  -->
                        <div class="btnList" v-if="!item.isPreview">
                            <span v-if="item.isPreview">
                                <div class="xinxin">
                                    <image
                                        :src="item.is_likes ? '/static/images/xinxin2.png' : '/static/images/xinxin0.png'">
                                    </image>
                                    <span>{{ formatToWan(item.likes) }}</span>
                                </div>
                                <div class="xinxin">
                                    <image src="/static/images/qipao.png">
                                    </image>
                                    <span>{{ formatToWan(item.comments) }}</span>
                                </div>
                                <div class="xinxin">
                                    <image src="/static/images/fl.png">
                                    </image>
                                </div>
                            </span>
                            <span v-else>
                                <div class="xinxin" @click="headleXin(item)">
                                    <image
                                        :src="item.is_likes ? '/static/images/xinxin2.png' : '/static/images/xinxin0.png'">
                                    </image>
                                    <span>{{ formatToWan(item.likes) }}</span>
                                </div>
                                <div class="xinxin" @click="headleXin2(item, index)">
                                    <image src="/static/images/qipao.png">
                                    </image>
                                    <span>{{ formatToWan(item.comments) }}</span>
                                </div>
                                <div class="xinxin" @click="headleXin3(item, index)">
                                    <image src="/static/images/fl.png">
                                    </image>
                                </div>
                            </span>
                        </div>
                        <div class="btnList" v-else>
                            <!-- <div class="xinxin">
                                <image
                                    :src="item.is_likes ? '/static/images/xinxin2.png' : '/static/images/xinxin0.png'">
                                </image>
                                <span>{{ formatToWan(item.likes) }}</span>
                            </div>
                            <div class="xinxin">
                                <image src="/static/images/qipao.png">
                                </image>
                            </div> -->
                            <div class="xinxin">
                                <image src="/static/images/fl.png">
                                </image>
                            </div>
                        </div>
                        <!-- </div> -->
                        <up-swiper :list="item.funplay_urls" indicator :autoplay="false" indicatorMode="line" circular
                            :indicatorStyle="'dot'" bgColor="#ffffff" :height="boxHeight - 30 + 'px'"></up-swiper>
                    </swiper-item>
                </swiper>
            </view>
        </view>
    </div>
    <upModal :modalShow="modalShow" :modalText1="t('Doyouwanttocancelattention')" :showImage="true" :isCancel="true"
        @cancel="modalShow = false" @cloos="cloos"></upModal>
</template>

<script setup lang="ts">
import upModal from '../../components/upModal.vue';
import { ref, reactive, onMounted } from 'vue'
import { onLoad, onShow, onBackPress } from '@dcloudio/uni-app';
import { attentionAndNot, funpaly, funpalyLike } from '@/api/index/index.js'
import { fashionplay, dynamic } from '@/api/index/index'
import { formatToWan } from '@/utils/numericalToW'
import { useI18n } from 'vue-i18n'
import { useDetails } from '@/stores/details';
const details = useDetails();

const { t } = useI18n()
const hendleReturnBtn = () => {// 返回键
    // #ifndef H5
    plus.storage.setItem('indexData', JSON.stringify(listData.value)) // 储存信息
    plus.storage.setItem('indexNum', itemNum.value) // 储存信息
    plus.storage.setItem('indexValue', listPage.value) // 储存信息
    // #endif
    uni.navigateBack()
}
// 手机物理返回键
onBackPress(() => {
    // #ifndef H5
    plus.storage.setItem('indexData', JSON.stringify(listData.value)) // 储存信息
    plus.storage.setItem('indexNum', itemNum.value) // 储存信息
    plus.storage.setItem('indexValue', listPage.value) // 储存信息
    // #endif
})
let scrollLeftTop = ref(0)// 顶部距离
let listData = ref([])
let optionsId = ref('');
let current = ref(0)
let startY = ref(0)
let endY = ref(0)
let swiperDuration = ref(0)// 垂直轮播图 滚动时间
const triggered = ref(false)
const btnLoading = ref(false)
const disablePullup = ref(false)// 禁止上拉、交互等
const swiperCurrent = ref(0)// 轮播图 默认显示的索引
const tapName = ref('')
const onRefresh = () => {// 下拉刷新函数
    triggered.value = true

    setTimeout(() => {
        triggered.value = false;
        uni.stopPullDownRefresh();// 关闭下来刷新动画效果
    }, 1000);
}
const onSwiperChange = (e: object) => {// 垂直轮播图 切换事件
    if (e.detail.current + 1 >= listData.value.length) { // 触底
        if (disablePullup.value) return
        swiperCurrent.value = e.detail.current// 重新设置显示的索引，防止回到上次索引进入的图片
        listPage.value++
        if (tapName.value == 1) {
            fashionplay(listPage.value).then((res: object) => {
                if (res.code == 200) {
                    if (!res.data) {
                        listPage.value--
                        uni.showToast({
                            title: t('Intheend'),
                            icon: 'none',
                            duration: 2000
                        })
                        return
                    }
                    listData.value.push(...res.data)
                } else {
                    uni.showToast({
                        title: `${res.msg}`,
                        icon: 'none',
                        duration: 2000
                    })
                    listPage.value--
                }
            })
        } else {
            dynamic(listPage.value).then((res: object) => {
                // console.log('res', res.data)
                if (res.code == 200) {
                    if (!res.data) {
                        listPage.value--
                        uni.showToast({
                            title: t('Intheend'),
                            icon: 'none',
                            duration: 2000
                        })
                        return
                    }
                    listData.value.push(...res.data)
                } else {
                    uni.showToast({
                        title: `${res.msg}`,
                        icon: 'none',
                        duration: 2000
                    })
                    listPage.value--
                }
            })
        }
    }
}
// const onBottom = () => {// 上拉加载函数
//     console.log('触底事件');
//     if (disablePullup.value) return
//     listPage.value++
//     fashionplay(listPage.value).then((res: object) => {
//         // console.log('res', res.data)
//         if (res.code == 200) {
//             if (!res.data) {
//                 listPage.value--
//                 uni.showToast({
//                     title: t('Intheend'),
//                     icon: 'none',
//                     duration: 2000
//                 })
//                 return
//             }
//             listData.value.push(...res.data)
//         } else {
//             uni.showToast({
//                 title: `${res.msg}`,
//                 icon: 'none',
//                 duration: 2000
//             })
//             listPage.value--
//         }
//     })
// }
// const swiperChange = (e: object) => {
//     console.log('swiperChange', e.detail.current);
// }
const isScrolling = ref(false)
const headleXin = (item: object) => {// 点赞按钮
    let para = {
        funplaycode: item.funplay_code,
        userCodeWithFun: item.user_code,
    }
    funpalyLike(para).then((res: object) => {
        if (res.code == 200) {
            item.is_likes = !item.is_likes
            if (item.is_likes) {
                item.likes++
            } else {
                item.likes--
            }
        } else {
            uni.showToast({
                title: `${res.mes}`,
                icon: 'error',
                duration: 2000
            })
        }
    }).catch((err: object) => {
        uni.showToast({
            title: `${err.mes}`,
            icon: 'error',
            duration: 2000
        })
    })
}
const headleXin2 = (item: object, index: number) => {// 评论按钮
    details.setItemIndex(index)// 保存当前跳转详情的索引
    if (item) {
        uni.navigateTo({
            url: `/pages/advertisements/articleDetails?forget=${t('comments')}&data=${item.funplay_code}`
        })
    }
}
const headleXin3 = (item: object, index: number) => {// 详情按钮
    details.setItemIndex(index)// 保存当前跳转详情的索引
    if (item) {
        uni.navigateTo({
            url: `/pages/advertisements/articleDetails?data=${item.funplay_code}`
        })
    }
}
const modalShow = ref(false)
const isAttention = ref(false)// 关注状态
const toUser = (data: object) => {// 头像点击
    uni.navigateTo({
        url: '/pages/me/userHomepage?data=' + data
    })
}
// 关注按钮
const attention = (item: object, index: number) => {
    btnLoading.value = true
    let para = {
        followUserCode: listData.value[index].user_code,
        isFollow: true,
    }
    attentionAndNot(para).then((res: object) => {
        if (res.code === 200) {
            // if (!isAttention.value) {
            item.is_follow = true
            // } else {
            //     modalShow.value = true;
            // }
            details.setItemData2(listData.value[details.itemIndex])
        } else {
            uni.showToast({
                title: `${res.mes}`,
                icon: 'error',
                duration: 2000
            })
        }
    }).catch((err: object) => {
        uni.showToast({
            title: `${err.mes}`,
            icon: 'error',
            duration: 2000
        })
    }).finally(() => {
        btnLoading.value = false
    })
}
let itemData = ref({})
let itemIndex = ref(0)
// 取消关注按钮
const attention2 = (item: object, index: number) => {
    itemData.value = item
    itemIndex.value = index
    modalShow.value = true
}
// 弹窗按钮
const cloos = () => {
    let para = {
        followUserCode: listData.value[itemIndex.value].user_code,
        isFollow: false,
    }
    attentionAndNot(para).then((res: object) => {
        modalShow.value = false
        if (res.code === 200) {
            itemData.value.is_follow = false
            details.setItemData2(listData.value[details.itemIndex])
        } else {
            uni.showToast({
                title: `${res.mes}`,
                icon: 'error',
                duration: 2000
            })
        }
    }).catch((err: object) => {
        uni.showToast({
            title: `${err.mes}`,
            icon: 'error',
            duration: 2000
        })
    }).finally(() => {
        modalShow.value = false
        btnLoading.value = false
    })
}
const boxHeight = ref(0)
const itemNum = ref(0) // 第几个内容索引
const listPage = ref(1)

// 滚动到对应内容
const scrollToComment = (num: number) => {
    swiperCurrent.value = num
};
onMounted(() => {
    uni.getSystemInfo({
        success: function (res) {
            boxHeight.value = res.screenHeight
        }
    });
    setTimeout(() => {
        swiperDuration.value = 300
    }, 300)
})
function isEmptyObject(obj) {
    return Object.keys(obj).length === 0;
}
onShow(() => {
    if (!isEmptyObject(details.itemData)) {// 判断对象是否为空，即是否操作了按钮
        listData.value[details.itemIndex].is_follow = details.itemData.if_follow
        listData.value[details.itemIndex].is_likes = details.itemData.if_likes
        listData.value[details.itemIndex].likes = details.itemData.likes
        listData.value[details.itemIndex].comments = details.itemData.comments
        details.setItemData2(listData.value[details.itemIndex])
        setTimeout(() => {
            details.setItemData({})
        }, 300)
    }
    if (optionsId.value) {
        listData.value = []
        funpaly(optionsId.value).then((res: object) => {
            if (res.code === 200) {
                listData.value.push(res.data)
            } else if (res.code === 13121208 || res.msg == '该帖子不存在') {
                uni.$emit('isDel', '1')
                uni.navigateBack()
            }
        }).catch((err: object) => {
            uni.showToast({
                title: `${err.mes}`,
                icon: 'error',
                duration: 2000
            })
        })
    }
})
onLoad((options: object) => {
    if (options.name) {
        tapName.value = options.name
    }
    // 预览跳转
    if (options.isYL == 1) {
        // #ifndef H5
        let indexData = JSON.parse(plus.storage.getItem('indexData2'))
        let indexNum = JSON.parse(plus.storage.getItem('indexNum2'))
        let indexValue = JSON.parse(plus.storage.getItem('indexValue2'))
        if (indexData) {
            listData.value = indexData
            swiperDuration.value = 0
        }
        if (indexNum) {
            itemNum.value = indexNum
            setTimeout(() => {
                scrollToComment(indexNum)
            }, 50)
        }
        if (indexValue) {
            listPage.value = indexValue
        }
        // #endif
    } else {
        // #ifndef H5
        let indexData = JSON.parse(plus.storage.getItem('indexData'))
        let indexNum = JSON.parse(plus.storage.getItem('indexNum'))
        let indexValue = JSON.parse(plus.storage.getItem('indexValue'))
        if (indexData) {
            listData.value = indexData
            swiperDuration.value = 0
        }
        if (indexNum) {
            itemNum.value = indexNum
            setTimeout(() => {
                scrollToComment(indexNum)
            }, 50)
        }
        if (indexValue) {
            listPage.value = indexValue
        }
        // #endif
        // #ifdef H5
        if (options.forget) {
            listData.value = JSON.parse(decodeURIComponent(options.forget))
            // console.log("数据集:", listData.value)
        }
        if (options.num) {
            itemNum.value = options.num
            setTimeout(() => {
                scrollToComment(options.num)
            }, 50)
        }
        if (options.page) {
            disablePullup.value = false
            listPage.value = options.page
        } else {
            disablePullup.value = true
        }
        // #endif
    }
});
</script>
<style scoped lang="scss">
.bodyBox {
    width: 100%;
    height: calc(100vh - 2rem);
    padding-top: 2rem;
    position: relative;
    // padding-top: var(--status-bar-height);

    .app-page {
        /* background: black; */
        height: 100%;
        width: 100vw;
        display: flex;
        justify-content: center;
        align-items: center;

        .page {
            width: 100%;
            height: 100%;
            // background: #f1f1f1;
            // font-size: 40px;
        }
    }


    // .mainBoxItem {
    //     width: 100%;
    //     height: calc(100%);
    //     position: absolute;
    //     top: 0;
    //     left: 0;
    //     z-index: 9999;

    ::v-deep .u-swiper__wrapper__item__wrapper__image {
        background-color: #000;

        div {
            background-size: contain !important;
        }
    }

    image {
        width: 100%;
        height: 100%;
        z-index: 9999;
    }

    .titleItem {
        max-width: 90%;
        color: #fff;
        display: inline-block;
        position: absolute;
        bottom: 3.2%;
        left: 3%;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        z-index: 9999;
    }

    .imgBox {
        width: 90%;
        color: #fff;
        position: absolute;
        bottom: 6%;
        left: 3%;
        display: flex;
        align-items: center;
        z-index: 9999;

        image {
            width: 80rpx;
            height: 80rpx;
            border-radius: 50%;
            margin-right: 10rpx;
        }

        .imgBoxBtnList {
            display: inline-block;

            .u-button {
                // max-width: 8rem;
                background-color: #fff;
                color: #000;
                border-radius: 15px;
                margin-left: 20rpx;
            }

            .pinkBtn {
                background-color: #de868f;
                color: #fff;
            }
        }
    }

    .btnList {
        color: #fff;
        position: absolute;
        bottom: 5%;
        right: 5%;
        z-index: 9999;

        .xinxin {
            margin-bottom: 30rpx;
            text-align: center;

            image {
                width: 2rem;
                height: 2rem;
                display: block;
                margin: 0 auto;
                margin-bottom: 20rpx;
            }

            span {
                font-size: 28rpx;
                display: block;
                text-align: center;
            }
        }
    }

    // }

    .mainBox {
        width: 100%;
        height: 100%;
        overflow-y: auto;

        .notice {
            width: 100%;
            height: 100vh;
            line-height: 80rpx;
            background: #f9f9f9;
            border-radius: 80rpx;
            margin: 0 auto;
            display: flex;

            .center {
                flex: 1;
                width: 100%;
                height: 100%;
                position: relative;

                uni-swiper {
                    height: 100% !important;
                }

                swiper {
                    width: 100%;

                    swiper-item {
                        width: 100%;
                        height: 100%;
                        font-size: 30rpx;
                        color: #666;
                        position: relative;
                    }
                }
            }
        }
    }

    .returnBtn {
        position: fixed;
        top: 2.5rem;
        left: 20rpx;
        z-index: 9999;
    }
}
</style>